package com.ypan.creator;

/**
 * @author: ypan
 * @date: 2021/3/11 20:45
 * @desc: 原型模式
 * 用于创建重复对象。需要实现Cloneable
 * 可以选择重写clone()方法。
 * clone分为浅克隆和深克隆。
 * 浅克隆只是克隆引用，对象还是一个。
 * 深克隆是对象也新创建了一个，如下：
 */
public class PrototypePattern {

    static class User implements Cloneable{
        private String name;
        private Integer age;

        User(String name,Integer age){
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }

        @Override
        protected User clone() throws CloneNotSupportedException {
//            return new User(this.name,this.age);
            return this;
        }
    }

    public static void main(String[] args) throws Exception{
        User user = new User("yy",22);
        User user1 = user.clone();
        System.out.println(user == user1);
    }

}
